<template>
  <div style="padding:20px 20px 40px 20px">
    <el-card shadow="hover">
      <el-form inline>
          <el-form-item>
              <el-input v-model="params.name" placeholder="请输入证书名称"></el-input>
          </el-form-item>
          <el-form-item>
              <el-input v-model="params.authorityName" placeholder="请输入机构名称"></el-input>
          </el-form-item>
          <el-form-item>
             <el-select v-model="params.cityId" placeholder="请选择省">
                <el-option
                v-for="item in provOp1"
                :key="item.id"
                :label="item.cityname"
                :value="item.id">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
             <el-select v-model="params.classifyId" placeholder="请选择机构分类">
                <el-option v-for="item in classList" :label="item.classifyName" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="search" >搜索</el-button>
            <el-button type="warning" size="small" @click="add" >新增</el-button>
            <el-button @click="cancelData" size="small"
            >重置</el-button
            >
          </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top:20px" shadow="hover">
      <el-table
        max-height="550"
        v-loading="loading"
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column
          prop="name"
          label="证书名称"
          align="center"
          min-width="150"
        ></el-table-column>
        <el-table-column
          prop="genreTitle"
          label="标题"
          align="center"
          min-width="150"
        ></el-table-column>
        <el-table-column
          label="证书logo"
          align="center"
          min-width="150"
        >
        <template slot-scope="scope">
            <img style="width:100px;height:100px" :src="showUrl + scope.row.logo" alt="">
        </template>
        </el-table-column>
        <el-table-column
          label="操作"
          min-width="230"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="ed(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="del(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- </el-card> -->
      <div class="pagination">
        <pagination
          v-show="pageTotal > 0"
          :total="pageTotal"
          :page.sync="params.pageNum"
          :limit.sync="params.pageSize"
          @pagination="getData00"
        />
      </div>
    </el-card>
    <el-dialog :title="title" :visible.sync="imgVisible" width="700px" :close-on-click-modal="false">
        <el-form style="height:700px;overflow: auto;" :model="form" ref="form" :rules="rules" label-width="130px">
            <el-form-item prop="name" label="证书名称">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item prop="genreTitle" label="标题">
                <el-input v-model="form.genreTitle"></el-input>
            </el-form-item>
             <el-form-item prop="title" label="seo标题">
                <el-input v-model="form.title"></el-input>
            </el-form-item>
             <el-form-item prop="keywords" label="keywords 关键词">
                <el-input v-model="form.keywords"></el-input>
            </el-form-item>
             <el-form-item prop="description" label="description 描述">
                <el-input v-model="form.description"></el-input>
            </el-form-item>
            <el-form-item prop="industry" label="适用行业">
                <el-input v-model="form.industry"></el-input>
            </el-form-item>
            <!-- <el-form-item prop="details" label="认证作用">
                <el-input v-model="form.details"></el-input>
            </el-form-item> -->
            <el-form-item prop="sort" label="排序">
                <el-input-number v-model="form.sort"></el-input-number>
            </el-form-item>
            <el-form-item  prop="classifyId" label="证书分类">
                <el-select placeholder="请选择证书分类" v-model="form.classifyId">
                    <el-option v-for="item in classList" :label="item.classifyName" :value="item.id" :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="authorityId" label="选择机构">
                <el-select :disabled="depIf" @change="getAuthName" v-model="form.authorityId" placeholder="请选择">
                    <el-option v-for="item in authOp" :key="item.id" :label="item.authorityName" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="CNAS/IFA">
               <el-select v-model="form.species" multiple  placeholder="请选择CNAS/IFA">
                    <el-option label="CNAS" value="CNAS"></el-option>
                    <el-option label="IFA" value="IFA"></el-option>
                </el-select>
            </el-form-item>
             <el-form-item label="服务价格" >
              <el-input v-model="form.price" ></el-input>
            </el-form-item>
             <el-form-item label="服务优势">
              <el-input v-model="form.advantage"></el-input>
            </el-form-item>
            <el-form-item label="版式排列">
              <el-radio-group v-model="form.muey">
                <el-radio :label="1">横板</el-radio>
                <el-radio :label="0">竖版</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否最热">
              <el-radio-group v-model="form.isHot">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否最新">
              <el-radio-group v-model="form.isNews">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否推荐">
              <el-radio-group v-model="form.isRec">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="cityIds" label="选择省">
                <el-select multiple v-model="form.cityIds" placeholder="请选择省">
                    <el-option  label="全国" :value="0"></el-option>
                    <el-option
                    v-for="item in provOp1"
                    :key="item.id"
                    :label="item.cityname"
                    :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item prop="logo" label="证书logo">
                <el-upload class="avatar-uploader" :action="upImage + '/cms/company/upload'" :show-file-list="false" :on-success="handleAvatarSuccess">
                <img v-if="form.logo" :src="showUrl + form.logo" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item prop="genrePice" label="证书样品">
               <el-upload
                :action="upImage + '/cms/company/upload'"
                list-type="picture-card"
                :file-list="form.genrePice"
                :on-success="handleAvatarSuccess1"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="项目概述">
              <Editor v-model="form.content" />
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="imgVisible = false" size="small">取消</el-button>
        <el-button @click="submitForm" type="primary" size="small"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {getList00 ,seleCity,sureAdd,sureEd,delSure,getAut,getFill} from '@/api/web/cer'
import Editor from "@/components/Editor";
import { queryGoodsCate} from "@/api/goods/goods";
import { log } from 'util';

export default {  
    components: {
        Editor
    },
    data(){
        return{
            dialogVisible:false,
            dialogImageUrl:'',
            classList:[],
            loading:true,
            tableData:[],
            headers: { Authorization: "Bearer " + getToken() },
            upImage: process.env.VUE_APP_BASE_API,
            form:{
                id:'',
                authorityName:'',
                linkman:'',
                phone:'',
                logo:'',
                details:'',
                sort:'',
                content:'',
                address:'',
                legalName:'',
                provinceId:'',
                cityId:'',
                areaId:'',
                capital:'',
                startDate:'',
                companyType:'',
                operateType:'',
                registered:'',
                creditCode:'',
                scopeRange:'',
                crantNo:'',
                scope:'',
                sample:'',
                price:'面议',
                advantage:'',
                species:''
            },
            depIf:false,
            genreTitle:'',
            imgVisible:false,
            // 省市区数组
            areOp:[],
            citOp:[],
            provOp:[],
            areOp1:[],
            citOp1:[],
            provOp1:[],
            // 分页
            params: {
                pageNum: 1,
                pageSize: 10,
                authorityName:'',
                provinceId:'',
                cityId:'',
                areaId:'',
            },
            pageTotal:0,
            rules: {
                authorityName: [
                    { required: true, message: '请输入机构名称', trigger: 'blur' },
                ],
                name:[
                    { required: true, message: '请输入证书名称', trigger: 'blur' },
                ],
                content: [
                    { required: true, message: '请输入机构简介', trigger: 'blur' }
                ],               
                legalName: [
                    { required: true, message: '请输入法定代表人姓名', trigger: 'blur' }
                ],   
                cityIds: [
                    { required: true, message: '请选择省', trigger: 'change' }
                ],
                areaId: [
                    { required: true, message: '请选择区县', trigger: 'change' }
                ],
                logo:[
                    { required: true, message: '请上传图片', trigger: 'change' }
                ],
                genrePice:[
                    { required: true, message: '请上传图片', trigger: 'change' }
                ]
            },
            // 机构选择
            authOp:[]
        }
    },
    methods:{
        // 搜索
        search() {
            this.params.pageNum = 1
            this.getData00()
        },
        // 重置搜索框
        cancelData() {
            this.params = {
                pageNum: 1,
                pageSize: 10,
                authorityName:'',
                provinceId:'',
                cityId:'',
                areaId:'',
            },
            this.getData00();
        },
        // 新增
        add() {
        this.getCity1('',1)
        this.title = '新增'
        this.form = {
            id:'',
            authorityName:'',
            linkman:'',
            phone:'',
            logo:'',
            details:'',
            sort:10,
            content:'',
            address:'',
            legalName:'',
            provinceId:'',
            cityIds:'',
            areaId:'',
            capital:'',
            startDate:'',
            companyType:'',
            operateType:'',
            registered:'',
            creditCode:'',
            scopeRange:'',
            crantNo:'',
            scope:'',
            genrePice:[],
            sample:'',
            price:'面议',
            advantage:'',
            species:'',
            description:'',
            genreTitle:'',
            keywords:'',
            title:'',
            authorityId:''
        }
        var dep = localStorage.getItem("deptId")
        if(dep != 100){
            let org = localStorage.getItem("orgId")
            if(org != 0){
                getFill(org).then(res => {
                    if(res.code == 200){
                        this.form.authorityId = res.data.id
                    }
                })
            }
        }
        this.imgVisible = true
        },
        // 编辑
        ed(row) {
            console.log(row)
            this.imgVisible = true
            this.$nextTick(() => {
                this.form = JSON.parse(JSON.stringify(row));
               
                if(this.form.cityIds != ''){
                    // console.log(this.form)
                    this.form.cityIds = this.form.cityIds.split(',')
                    this.form.cityIds = this.form.cityIds.map(item => Number(item))
                }else {
                    this.form.cityIds = []
                }
                this.form.genrePice = JSON.parse(JSON.stringify(this.form.piceList));
                if(this.form.species != ''){
                      this.form.species = this.form.species.split(',')
                }else{
                    this.form.species =[]
                }
            })
            this.getCity1('',1)
            this.title = '编辑'
        },
        // 传值给机构名称
        getAuthName() {
            for(let i = 0;i<this.authOp.length;i++){
                if(this.authOp[i].id == this.form.authorityId){
                    this.form.authorityName = this.authOp[i].authorityName
                }
            }
        },

        /**
         * 处理选择全国情况时 函数
         * @param {Array} citys 已选择城市id
         * @returns {Array}
         */
        filterCitys(citys){
            // console.log('filterCitys',citys.includes(0),citys,citys===0);
            if(citys==='0'){
            // if(citys.includes(0)){
                let newArr = []
                this.provOp1.map(item=>{
                    newArr.push(item['id'])
                })
                console.log(newArr)
                return newArr.join()
            }else{
                return citys
            }
        },

        // 提示全国选中状态
        totalCitys(){
            const arr = this.form.cityIds
            if(arr.includes(0) && arr.length > 1){
                this.$message.info('选中全国请取消其他省市！')
                return false
            }
            return true
        },
        
        // 提交
        submitForm() {
            if(!this.totalCitys()) return
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.form.cityIds = this.form.cityIds.toString();
                    console.log('submit-citys',this.form.cityIds);
                    this.form.genrePice = JSON.stringify(this.form.genrePice)
                    this.form.species = this.form.species.toString()
                     if(this.title == '新增'){
                        let cityIds = this.filterCitys(this.form.cityIds)
                        console.log('新增-cityIds',cityIds);
                        let copyForm = Object.assign({},this.form,{cityIds})
                        console.log(copyForm,'------------copy------------------');
                        sureAdd(copyForm).then(res => {
                            if(res.code == 200){
                                this.$message.success('新增成功')
                                this.imgVisible = false
                                this.getData00()
                            }
                        })
                    }else {
                        let cityIds = this.filterCitys(this.form.cityIds)
                        let copyForm = Object.assign({},this.form,{cityIds})
                        // return
                        sureEd(copyForm).then(res => {
                            if(res.code == 200){
                            this.$message.success('编辑成功')
                                this.imgVisible = false
                                this.getData00()
                            }
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
                });
        },
        // 删除
        del(row){
            this.$confirm('此操作将删除该机构, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                delSure(row.id).then(res => {
                    if(res.code == 200){
                        this.$message.success('删除成功')
                        this.getData00()
                    }
                })
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });

        },
        // 拼接
        addressChange() {
            this.form.address = this.change(this.form.provinceId,1) + this.change(this.form.cityId,2) + this.change(this.form.areaId,3) 
        },
        // 拼接方法
        change(id,type){
            if(type == 1){
                for(let i =0;i<this.provOp1.length;i++){
                    if(this.provOp1[i].id == id){
                        return this.provOp1[i].cityname
                    }
                }
            // 获取市
            }else if(type == 2){
                for(let i =0;i<this.citOp1.length;i++){
                    if(this.citOp1[i].id == id){
                        return this.citOp1[i].cityname
                    }
                }
            }else if(type == 3){
                for(let i =0;i<this.areOp1.length;i++){
                    if(this.areOp1[i].id == id){
                        return this.areOp1[i].cityname
                    }
                }
            }
        },
        // 上传
        handleAvatarSuccess(res) {
            if(res.code == 200){
                this.form.logo = res.data
            }
        },
        // 上传多张
        handleAvatarSuccess1(res) {
            if(res.code == 200){
                let data ={
                    url:this.showUrl + res.data
                }
              this.form.genrePice.push(data)
            }
        },
        handleRemove(file, fileList) {
            this.form.genrePice = fileList
        },
        // 获取省市区
        getCity1(id,type) {
            let region = {
                  type:type,
                  pid:id
                }
            seleCity(region).then(res => {
                if (res.code == 200) {
                    this.provOp1 = res.rows;
                    // console.log('prop1',this.prop1);
                }
            })
        },
        getCate() {
            let data = {
                pageNum:1,
                pageSize:1000
            }
            queryGoodsCate(data).then(res => {
                if(res.code == 200){
                    this.classList = res.rows
                }
            })
        },
        // 获取全部机构
        getAuth(){
            let data = {
                state:1,
                pageNum:1,
                pageSize:10000
            }
            getAut(data).then(res => {
                if(res.code == 200){
                    this.authOp = res.rows
                }
            })
        },
        // 获取列表
        getData00() {
            getList00(this.params).then(res => {
                if(res.code == 200){
                    this.tableData = res.rows;
                    this.pageTotal = res.total;
                    this.loading = false;
                }
            })
        }
    },
    created(){
        var dep = localStorage.getItem("deptId")
        if(dep != 100){
            this.depIf = true
        }else{
            this.depIf = false
        }
        this.getData00()
        this.getCate('',1)
        this.getCity1('',1)
        this.getAuth()
    }
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
        /* width: 80%;
    height: 80%; */
        width: 150px;
    height: 150px;
    color: #8c939d;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
</style>